import { useQuery } from '@tanstack/react-query'

import { AuthAPI } from '../api'
import { useAuthStore } from '../store/authStore'

export const useCurrentUser = () => {
  const setUser = useAuthStore((state) => state.setUser)
  const cachedUser = useAuthStore((state) => state.user)

  return useQuery({
    queryKey: ['me'],
    queryFn: async () => {
      const profile = await AuthAPI.getProfile()
      setUser(profile)
      return profile
    },
    initialData: cachedUser ?? undefined,
    staleTime: 0,
    refetchOnMount: 'always',
    refetchOnReconnect: 'always',
    refetchOnWindowFocus: true,
  })
}

export default useCurrentUser
